const ioHook = require("iohook");
const { MouseHandler } = require('./src/data/mouse');
const { MouseDao } = require('./src/back/dao/mouse');

/* =======  Listent Key Events ============ */
ioHook.on('keyup', event => {
    // Alt Key Need Press.
    if (!event.altKey) return false;

    // On Press Key F6
    if (event.keycode === 64) {
        MouseHandler.flag = MouseHandler.flag ^ 1;
        console.log('MouseHandler Flag : %d', MouseHandler.flag);
        if (MouseHandler.flag) {
            MouseHandler.logPos(event => {
                console.log('Log POS', event);
            });
        } else {
            MouseHandler.stopPos(() => {
                console.log('Stop POS');
                // Don't Save Empty Stack;
                if (!MouseHandler.posStack.length) return;
                MouseDao.logPos(MouseHandler.posStack, () => {
                    MouseHandler.posStack.length = 0;
                });
            });
        }
        return true;
    }

    // On Press Key F7
    if (event.keycode === 65) {
        MouseDao.getLastPos(row => {
            console.log('Test Pos ID : ', row.id);
            MouseHandler.clickPosStack(JSON.parse(row.pos));
        });
        return true;
    }
})

ioHook.start();

/* =======  Koa Server ================= */
const { Loop } = require('./src/back/loop');
Loop();

/* =======  Koa Server ================= */
const Koa = require('koa');
const app = new Koa();
const KoaBody = require('koa-body');
const Websocket = require('koa-easy-ws');

const { router } = require('./src/back/action/router');

app.use(Websocket())
    .use(KoaBody())
    .use(router.routes())
    .use(router.allowedMethods());

app.listen(8081);

